<template>
    <div ref="chartRef" :style="{ height }"></div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, watch } from 'vue';
  import * as echarts from 'echarts';
  
  const props = defineProps({
    data: {
      type: Object,
      required: true
    },
    height: {
      type: String,
      default: '300px'
    }
  });
  
  const chartRef = ref();
  let chart: echarts.ECharts | null = null;
  
  const initChart = () => {
    if (!chartRef.value) return;
    
    chart = echarts.init(chartRef.value);
    updateChart();
  };
  
  const updateChart = () => {
    if (!chart) return;
  
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: props.data.datasets.map(dataset => dataset.label)
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: props.data.labels
      },
      yAxis: {
        type: 'value'
      },
      series: props.data.datasets.map(dataset => ({
        name: dataset.label,
        type: 'bar',
        data: dataset.data,
        itemStyle: {
          color: dataset.backgroundColor
        }
      }))
    };
  
    chart.setOption(option);
  };
  
  watch(() => props.data, updateChart, { deep: true });
  
  onMounted(() => {
    initChart();
    window.addEventListener('resize', () => chart?.resize());
  });
  
  onUnmounted(() => {
    chart?.dispose();
    window.removeEventListener('resize', () => chart?.resize());
  });
  </script>